import { isString, isObject } from '@web-utils/core'
import { cimPushManager } from '@/util/web-socket'
import store from '@/store'

export default {
  beforeCreate() {
    const callbacks = this.$options.message
    if (callbacks) {
      this.$_message_events = []
      for (const action in callbacks) {
        const handler = data => {
          callbacks[action].call(this, data)
        }
        cimPushManager.addMessageListener(action, handler)
        this.$_message_events.push({ action, handler })
      }
    }
  },
  beforeDestroy() {
    if (this.$_message_events) {
      for (const listener of this.$_message_events) {
        cimPushManager.removeMessageListener(listener.action, listener.handler)
      }
    }
  },
  methods: {
    async sendMessageToServer(msg) {
      if (isString(msg) || isObject(msg)) {
        await cimPushManager.sendMessage({ content: msg, receiver: store.state.user.sysUser.userId })
      }
    }
  }
}
